package org.framework.wu.framework.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 基于内存的消息队列实现
 */
public class InMemoryMessageQueue implements MessageQueue {
    
    private final BlockingQueue<Message> queue;
    private final String name;
    private boolean closed = false;
    
    public InMemoryMessageQueue(String name, int capacity) {
        this.name = name;
        this.queue = new LinkedBlockingQueue<>(capacity);
    }
    
    @Override
    public boolean send(Message message) {
        if (closed) {
            throw new IllegalStateException("Queue is closed");
        }
        
        try {
            // 尝试在1秒内将消息放入队列
            return queue.offer(message, 1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
    
    @Override
    public Message receive() {
        if (closed) {
            throw new IllegalStateException("Queue is closed");
        }
        
        try {
            // 阻塞等待直到有消息可用
            return queue.take();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        }
    }
    
    @Override
    public Message receiveNoWait() {
        if (closed) {
            throw new IllegalStateException("Queue is closed");
        }
        
        return queue.poll();
    }
    
    @Override
    public int size() {
        return queue.size();
    }
    
    @Override
    public boolean isEmpty() {
        return queue.isEmpty();
    }
    
    @Override
    public void close() {
        closed = true;
        queue.clear();
    }
    
    public String getName() {
        return name;
    }
}
